/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controller;

import controller.exceptions.NonexistentEntityException;
import entidades.Cardapio;
import entidades.Cliente;
import entidades.Ingredientes;
import entidades.Promocao;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;

/**
 *
 * @author Renato
 */
public class CardapioJpaController {

    private Cardapio cardapio;
    private Integer id;
    private String produto;
    private String descricao;
    private double preco;
    private List<Ingredientes> ingredientesCollection1;
    private Collection<Cardapio> listCardapio;
   

    public String novoCardapio(){
        this.cardapio = new Cardapio();
        return "novoCardapio";
    }

    public String listarCardapio(){
        return "listarCardapio";
    }

    public CardapioJpaController() {
        emf = Persistence.createEntityManagerFactory("restaurantePU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public String create() {
        if (cardapio.getClienteCollection() == null) {
            cardapio.setClienteCollection(new HashSet<Cliente>());
        }
        if (cardapio.getIngredientesCollection() == null) {
            cardapio.setIngredientesCollection((List<Ingredientes>) new HashSet<Ingredientes>());
        }
        if (cardapio.getPromocaoCollection() == null) {
            cardapio.setPromocaoCollection(new HashSet<Promocao>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Set<Cliente> attachedClienteCollection = new HashSet<Cliente>();
            for (Cliente clienteCollectionClienteToAttach : cardapio.getClienteCollection()) {
                clienteCollectionClienteToAttach = em.getReference(clienteCollectionClienteToAttach.getClass(), clienteCollectionClienteToAttach.getId());
                attachedClienteCollection.add(clienteCollectionClienteToAttach);
            }
            cardapio.setClienteCollection(attachedClienteCollection);
            List<Ingredientes> attachedIngredientesCollection = new ArrayList<Ingredientes>();
            for (Ingredientes ingredientesCollectionIngredientesToAttach : cardapio.getIngredientesCollection()) {
                ingredientesCollectionIngredientesToAttach = em.getReference(ingredientesCollectionIngredientesToAttach.getClass(), ingredientesCollectionIngredientesToAttach.getId());
                attachedIngredientesCollection.add(ingredientesCollectionIngredientesToAttach);
            }
            cardapio.setIngredientesCollection(attachedIngredientesCollection);
            Set<Promocao> attachedPromocaoCollection = new HashSet<Promocao>();
            for (Promocao promocaoCollectionPromocaoToAttach : cardapio.getPromocaoCollection()) {
                promocaoCollectionPromocaoToAttach = em.getReference(promocaoCollectionPromocaoToAttach.getClass(), promocaoCollectionPromocaoToAttach.getId());
                attachedPromocaoCollection.add(promocaoCollectionPromocaoToAttach);
            }
            cardapio.setPromocaoCollection(attachedPromocaoCollection);
            em.persist(cardapio);
            for (Cliente clienteCollectionCliente : cardapio.getClienteCollection()) {
                clienteCollectionCliente.getCardapioCollection().add(cardapio);
                clienteCollectionCliente = em.merge(clienteCollectionCliente);
            }
            for (Ingredientes ingredientesCollectionIngredientes : cardapio.getIngredientesCollection()) {
                ingredientesCollectionIngredientes.getCardapioCollection().add(cardapio);
                ingredientesCollectionIngredientes = em.merge(ingredientesCollectionIngredientes);
            }
            for (Promocao promocaoCollectionPromocao : cardapio.getPromocaoCollection()) {
                promocaoCollectionPromocao.getCardapioCollection().add(cardapio);
                promocaoCollectionPromocao = em.merge(promocaoCollectionPromocao);
            }
            em.getTransaction().commit();

            FacesMessage fm = new FacesMessage("Cardapio '"+cardapio.getProduto()+"' inserido");
            FacesContext.getCurrentInstance().addMessage("Cardapio inserido", fm);
        } finally {
            if (em != null) {
                em.close();
            }
        }
        return "listarCardapio";
    }

    public void edit(Cardapio cardapio) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Cardapio persistentCardapio = em.find(Cardapio.class, cardapio.getId());
            Set<Cliente> clienteCollectionOld = persistentCardapio.getClienteCollection();
            Set<Cliente> clienteCollectionNew = cardapio.getClienteCollection();
            List<Ingredientes> ingredientesCollectionOld = persistentCardapio.getIngredientesCollection();
            List<Ingredientes> ingredientesCollectionNew = cardapio.getIngredientesCollection();
            Set<Promocao> promocaoCollectionOld = persistentCardapio.getPromocaoCollection();
            Set<Promocao> promocaoCollectionNew = cardapio.getPromocaoCollection();
            Set<Cliente> attachedClienteCollectionNew = new HashSet<Cliente>();
            for (Cliente clienteCollectionNewClienteToAttach : clienteCollectionNew) {
                clienteCollectionNewClienteToAttach = em.getReference(clienteCollectionNewClienteToAttach.getClass(), clienteCollectionNewClienteToAttach.getId());
                attachedClienteCollectionNew.add(clienteCollectionNewClienteToAttach);
            }
            clienteCollectionNew = attachedClienteCollectionNew;
            cardapio.setClienteCollection(clienteCollectionNew);
            Set<Ingredientes> attachedIngredientesCollectionNew = new HashSet<Ingredientes>();
            for (Ingredientes ingredientesCollectionNewIngredientesToAttach : ingredientesCollectionNew) {
                ingredientesCollectionNewIngredientesToAttach = em.getReference(ingredientesCollectionNewIngredientesToAttach.getClass(), ingredientesCollectionNewIngredientesToAttach.getId());
                attachedIngredientesCollectionNew.add(ingredientesCollectionNewIngredientesToAttach);
            }
            ingredientesCollectionNew = (List<Ingredientes>) attachedIngredientesCollectionNew;
            cardapio.setIngredientesCollection(ingredientesCollectionNew);
            Set<Promocao> attachedPromocaoCollectionNew = new HashSet<Promocao>();
            for (Promocao promocaoCollectionNewPromocaoToAttach : promocaoCollectionNew) {
                promocaoCollectionNewPromocaoToAttach = em.getReference(promocaoCollectionNewPromocaoToAttach.getClass(), promocaoCollectionNewPromocaoToAttach.getId());
                attachedPromocaoCollectionNew.add(promocaoCollectionNewPromocaoToAttach);
            }
            promocaoCollectionNew = attachedPromocaoCollectionNew;
            cardapio.setPromocaoCollection(promocaoCollectionNew);
            cardapio = em.merge(cardapio);
            for (Cliente clienteCollectionOldCliente : clienteCollectionOld) {
                if (!clienteCollectionNew.contains(clienteCollectionOldCliente)) {
                    clienteCollectionOldCliente.getCardapioCollection().remove(cardapio);
                    clienteCollectionOldCliente = em.merge(clienteCollectionOldCliente);
                }
            }
            for (Cliente clienteCollectionNewCliente : clienteCollectionNew) {
                if (!clienteCollectionOld.contains(clienteCollectionNewCliente)) {
                    clienteCollectionNewCliente.getCardapioCollection().add(cardapio);
                    clienteCollectionNewCliente = em.merge(clienteCollectionNewCliente);
                }
            }
            for (Ingredientes ingredientesCollectionOldIngredientes : ingredientesCollectionOld) {
                if (!ingredientesCollectionNew.contains(ingredientesCollectionOldIngredientes)) {
                    ingredientesCollectionOldIngredientes.getCardapioCollection().remove(cardapio);
                    ingredientesCollectionOldIngredientes = em.merge(ingredientesCollectionOldIngredientes);
                }
            }
            for (Ingredientes ingredientesCollectionNewIngredientes : ingredientesCollectionNew) {
                if (!ingredientesCollectionOld.contains(ingredientesCollectionNewIngredientes)) {
                    ingredientesCollectionNewIngredientes.getCardapioCollection().add(cardapio);
                    ingredientesCollectionNewIngredientes = em.merge(ingredientesCollectionNewIngredientes);
                }
            }
            for (Promocao promocaoCollectionOldPromocao : promocaoCollectionOld) {
                if (!promocaoCollectionNew.contains(promocaoCollectionOldPromocao)) {
                    promocaoCollectionOldPromocao.getCardapioCollection().remove(cardapio);
                    promocaoCollectionOldPromocao = em.merge(promocaoCollectionOldPromocao);
                }
            }
            for (Promocao promocaoCollectionNewPromocao : promocaoCollectionNew) {
                if (!promocaoCollectionOld.contains(promocaoCollectionNewPromocao)) {
                    promocaoCollectionNewPromocao.getCardapioCollection().add(cardapio);
                    promocaoCollectionNewPromocao = em.merge(promocaoCollectionNewPromocao);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id1 = cardapio.getId();
                if (findCardapio(id1) == null) {
                    throw new NonexistentEntityException("The cardapio with id " + id1 + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Cardapio cardapio;
            try {
                cardapio = em.getReference(Cardapio.class, id);
                cardapio.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The cardapio with id " + id + " no longer exists.", enfe);
            }
            Set<Cliente> clienteCollection = cardapio.getClienteCollection();
            for (Cliente clienteCollectionCliente : clienteCollection) {
                clienteCollectionCliente.getCardapioCollection().remove(cardapio);
                clienteCollectionCliente = em.merge(clienteCollectionCliente);
            }
            List<Ingredientes> ingredientesCollection = cardapio.getIngredientesCollection();
            for (Ingredientes ingredientesCollectionIngredientes : ingredientesCollection) {
                ingredientesCollectionIngredientes.getCardapioCollection().remove(cardapio);
                ingredientesCollectionIngredientes = em.merge(ingredientesCollectionIngredientes);
            }
            Set<Promocao> promocaoCollection = cardapio.getPromocaoCollection();
            for (Promocao promocaoCollectionPromocao : promocaoCollection) {
                promocaoCollectionPromocao.getCardapioCollection().remove(cardapio);
                promocaoCollectionPromocao = em.merge(promocaoCollectionPromocao);
            }
            em.remove(cardapio);
            em.getTransaction().commit();
            FacesMessage fm = new FacesMessage("Cardapio '"+cardapio.getProduto()+"' excluido");
            FacesContext.getCurrentInstance().addMessage("Cardapio excluido", fm);
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Cardapio> findCardapioEntities() {
        return findCardapioEntities(true, -1, -1);
    }

    public List<Cardapio> getfindCardapioEntities() {
        return findCardapioEntities(true, -1, -1);
    }

    public List<Cardapio> findCardapioEntities(int maxResults, int firstResult) {
        return findCardapioEntities(false, maxResults, firstResult);
    }

    private List<Cardapio> findCardapioEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Cardapio as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Cardapio findCardapio(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Cardapio.class, id);
        } finally {
            em.close();
        }
    }

    public int getCardapioCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Cardapio as o").getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getProduto() {
        return produto;
    }

    public void setProduto(String produto) {
        this.produto = produto;
    }

    public String getDescricao() {
        return descricao;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }

    public double getPreco() {
        return preco;
    }

    public void setPreco(double preco) {
        this.preco = preco;
    }

    public Cardapio getCardapio() {
        return cardapio;
    }

    public void setCardapio(Cardapio cardapio) {
        this.cardapio = cardapio;
    }

    public List<Ingredientes> getingredientesCollection1() {
        return ingredientesCollection1;
    }

    public void setingredientesCollection1(List<Ingredientes> ingredientesCollection1) {
        this.ingredientesCollection1 = ingredientesCollection1;
    }

    public Collection<Cardapio> getlistCardapio(){
        listCardapio = getfindCardapioEntities();
        return listCardapio;
    }

    public void setlistCardapio(Collection<Cardapio> listCardapio){
        this.listCardapio = listCardapio;
    }


}
